package com.example.httplibrary.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Locale;

/**
 * @author 李巷阳
 * @version V1.0
 * @Description: (文件工具类)
 * @date 2018/8/15
 */
public class FileUtils {

    private static final String LOG_TAG = "FileUtils";

    private static final double KB = 1024.0;
    private static final double MB = KB * KB;
    private static final double GB = KB * KB * KB;
    private String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;

    /**
     * 获取文件扩展名
     *
     * eg：askahj1145asd.drm
     *
     * 得到drm
     *
     * @param filename
     * @return
     */
    public static String getExtFromFileName(String filename) {
        if (filename == null) {
            return "";
        }

        int dotPosition = filename.lastIndexOf('.');
        if (dotPosition != -1) {
            return filename.substring(dotPosition + 1);
        }
        return "";
    }

    /***
     * 获取文件名（不带扩展名）
     *
     * eg：askahj1145asd.drm
     *
     * 得到askahj1145asd
     *
     * @param filename
     * @return
     */
    public static String getNameFromFileName(String filename) {
        if (filename == null) {
            return "";
        }

        int dotPosition = filename.lastIndexOf('.');
        if (dotPosition != -1) {
            return filename.substring(0, dotPosition);
        }
        return "";
    }

    /**
     * 从文件路径获取文件的上层路径
     *
     * eg：/suizhi/file/askahj1145asd.drm
     *
     * 得到/suizhi/file
     *
     * @param filepath
     * @return
     */
    public static String getPathFromFilePath(String filepath) {
        if (filepath == null) {
            return "";
        }

        int pos = filepath.lastIndexOf('/');
        if (pos != -1) {
            return filepath.substring(0, pos);
        }
        return "";
    }
    /**
     * 从文件路径获取文件名
     *
     * eg：/suizhi/file/askahj1145asd.drm
     *
     * 得到askahj1145asd.drm
     *
     * @param filepath
     * @return
     */
    public static String getNameFromFilePath(String filepath) {
        if (filepath == null) {
            return "";
        }

        int pos = filepath.lastIndexOf('/');
        if (pos != -1) {
            return filepath.substring(pos + 1);
        }
        return "";
    }

    /**
     * 获取文件夹下子文件得名字
     *
     * eg：/suizhi/file/abc
     *
     * 得到abc
     *
     * @return
     */
    public static ArrayList getSubunitFileName(String filePath) {
        ArrayList al_Subunit_file = new ArrayList<String>();
        File f = new File(filePath);
        File[] files = f.listFiles();// 列出所有文件
        // 将所有文件存入list中
        if (files != null) {
            int count = files.length;// 文件个数
            for (int i = 0; i < count; i++) {
                File file = files[i];
                al_Subunit_file.add(file.getName());
            }
        }

        return al_Subunit_file;

    }
    public static String getSdDirectory() {
        return Environment.getExternalStorageDirectory().getPath();
    }
    /**
     * 获取目录文件大小
     *
     * @param dir
     * @return
     */
    public static long getDirSize(File dir) {
        if (dir == null) {
            return 0;
        }
        if (!dir.isDirectory()) {
            return 0;
        }
        long dirSize = 0;
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                dirSize += file.length();
            } else if (file.isDirectory()) {
                dirSize += file.length();
                dirSize += getDirSize(file); // 递归调用继续统计
            }
        }
        return dirSize;
    }
    /**
     * 格式化显示文件大小 eg:2G;2.3M（小数位不为0显示一位小数，小数位为0不显示小数位）
     *
     * @param size
     * @return
     */
    public static String convertStorage(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;

        if (size >= gb) {
            return String.format(Locale.getDefault(),"%.1fG", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(Locale.getDefault(),f > 100 ? "%.0fM" : "%.1fM", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(Locale.getDefault(),f > 100 ? "%.0fKB" : "%.1fKB", f);
        } else
            return String.format(Locale.getDefault(),"%dB", size);
    }

    /**
     * 根据文件绝对路径生成文件
     *
     * @param filePath
     *            文件绝对路径
     * @return
     */
    public static File createFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 获取文件大小
     *
     * @param filePath
     * @return
     */
    public static long getFileSize(String filePath) {
        long size = 0;

        File file = new File(filePath);
        if (file != null && file.exists()) {
            size = file.length();
        }
        return size;
    }

    /**
     * 检查路径是否存在
     *
     * @param path
     * @return
     */
    public static boolean checkFilePathExists(String path) {
        return new File(path).exists();
    }

    /**
     * 新建目录
     *
     * @param directoryName
     *            目录全路径
     * @return
     */
    public static boolean createDirectory(String directoryName) {
        if (checkFilePathExists(directoryName)) {
            return true;
        }
        return !directoryName.equals("") ? new File(directoryName).mkdirs() : false;
    }

    /**
     * 删除文件
     *
     * @param filePath
     */
    public static boolean deleteFileWithPath(String filePath) {
        SecurityManager checker = new SecurityManager();
        File f = new File(filePath);
        checker.checkDelete(filePath);
        if (f.isFile()) {
            f.delete();
            return true;
        }
        return false;
    }

    /**
     * 删除文件夹 param folderPath 文件夹完整绝对路径
     */

    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除指定文件夹下所有文件
     *
     * @param path
     *            文件夹完整绝对路径
     */

    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 在SD卡上创建文件
     *
     * @param filename
     * @param dir
     * @return
     */
    public File createFileInSDCard(String filename, String dir) throws IOException {
        File file = new File(SDCardRoot + dir + File.separator + filename);
        file.createNewFile();
        return file;
    }

    /**
     * 在SD卡上创建目录
     *
     * @param dir
     * @return
     */
    public File createDirInSDCard(String dir) {
        File dirFile = new File(SDCardRoot + dir + File.separator);
        dirFile.mkdir();
        return dirFile;
    }


    /**
     * 获取本地文件的内容
     * @param path
     * @return
     */
    public static String getFileFromSD(String path) {
        String result = "";

        try {
            FileInputStream f = new FileInputStream(path);
            BufferedReader bis = new BufferedReader(new InputStreamReader(f));
            String line = "";
            while ((line = bis.readLine()) != null) {
                result += line;
            }
            Log.e("","");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 获取cache路径
     *
     * @param context
     * @return
     */
    public static String getDiskCachePath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            File externalCacheDir = context.getExternalCacheDir();
            if (externalCacheDir == null) {// 有些手机需要通过自定义目录
                externalCacheDir = new File(Environment.getExternalStorageDirectory(), "Android/data/" + context.getPackageName() + "/cache/");
            }
            return externalCacheDir.getPath();
        } else {
            return context.getCacheDir().getPath();
        }
    }

    /**
     * 保存图片到相册中
     */
    public static void saveImageToGallery(final Context context, Bitmap bitmap) {
        // 首先保存图片
        File file = null;
        String fileName = System.currentTimeMillis() + ".jpg";
        File root = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
        File dir = new File(root, "images");
        if (dir.mkdirs() || dir.isDirectory()) {
            file = new File(dir, fileName);
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 通知图库更新
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            MediaScannerConnection.scanFile(context, new String[]{file.getAbsolutePath()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                            mediaScanIntent.setData(uri);
                            context.sendBroadcast(mediaScanIntent);
                        }
                    });
        } else {
            String relationDir = file.getParent();
            File file1 = new File(relationDir);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
        }
    }


    public static String getAudioFileName(String moegoCode,String preflix){

        return preflix+"moego_invitation_record"+moegoCode+".mp3";

    }
}
